package ltd.hxya.novel.book.controller;


import io.swagger.annotations.ApiParam;
import ltd.hxya.novel.book.entity.BookIndex;
import ltd.hxya.novel.book.feign.UserFeignService;
import ltd.hxya.novel.book.service.IBookIndexService;
import ltd.hxya.novel.common.exception.NovelGlobalException;
import ltd.hxya.novel.common.vo.BookIndexVo;
import ltd.hxya.novel.common.bean.Result;
import ltd.hxya.novel.common.constant.JwtConstant;
import ltd.hxya.novel.common.vo.BookContentParam;
import ltd.hxya.novel.common.vo.UserReadHistoryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 小说目录表 前端控制器
 * </p>
 *
 * @author hxya
 * @since 2022-09-13
 */
@RestController
@RequestMapping("/book/bookIndex")
public class BookIndexController {

    @Autowired
    private IBookIndexService bookIndexService;

    @Autowired
    private UserFeignService userFeignService;

    /**
     * 根据id获得小说的章节，并保存到Redis中
     */

    @PostMapping("/listBookIndex")
    public Result<List<BookIndexVo>> listBookIndex(@ApiParam("小说id") String bookId, @ApiParam("排序方式，0表示降序排列，1表示升序排列") Integer sort) {
        List<BookIndexVo> bookIndexVos = bookIndexService.bookIndex(bookId, sort);

        return Result.success(bookIndexVos);
    }

    /**
     * 查询下一章的id
     */
    @PostMapping("/nextAndPreIndexId")
    public Result<Map<Integer, String>> nextAndPreIndexId(BookContentParam param) {
        Map<Integer, String> indexId = bookIndexService.nextAndPreIndexId(param);

        return Result.success(indexId);
    }


    @GetMapping("/bookLastIndex/{bookId}")
    public Result<UserReadHistoryVo> bookLastIndex(@PathVariable("bookId") String bookId, HttpServletRequest request){
        //判断是否登录，如果登录，调用user服务远程接口，如果未登录，查询第一章
        String token = request.getHeader(JwtConstant.TOKEN_HEADER_KEY);
        UserReadHistoryVo userReadHistoryVo = null;
        if (StringUtils.isEmpty(token)){
            userReadHistoryVo = bookIndexService.bookLastIndex(bookId);
            return Result.success(userReadHistoryVo);
        }

        Result<UserReadHistoryVo> result = userFeignService.listBook(bookId);

        userReadHistoryVo = result.getData();
        //在bookshelf中查询出num的值，封装到bookshelf中
        if (userReadHistoryVo==null){
            //没有阅读过这本书，查询第一章的id
            userReadHistoryVo = bookIndexService.bookLastIndex(bookId);
        }
        BookIndex bookIndex = bookIndexService.getById(userReadHistoryVo.getPreContentId());
        userReadHistoryVo.setIndexNum(bookIndex.getIndexNum());

        return Result.success(userReadHistoryVo);
    }


}
